<?php

/**
 * @author Murat Cem YALIN <muratcem@gmail.com>
 * @copyright 2014 muratcem.com - walkerPHP.com
 * @license http://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3
 * @version 1.0.1
 */

namespace core\Controller;

use core\Config\Config;
use \core\Session\Session;
use \core\HTML\HTML;

class Controller implements IController{
    /**
     * function to check if a function is public or not
     *
     * @param string $function
     * @return bool
     */
    public function isPublic($function){
        $className  = get_class($this);
        $class      = new \ReflectionClass($className);
        $methods    = $class->getMethods(\ReflectionMethod::IS_PUBLIC);
        for ($i=0; $i<count($methods); $i++){
            if ($methods[$i]->class == $className && $methods[$i]->name == $function){
                return TRUE;
            }
        }
        return FALSE;
    }

    /**
     * we will call the function from $_GET['f'] variable
     * if the function is public or if the $_GET['f']
     * var is not set then call the "main" function
     *
     * if $needAuth variable is set TRUE on the controller
     * then Controller class will check for the Authentication
     * and access levels
     */
    public function __construct(){
        $function = (isset($_GET['f']) && method_exists($this, $_GET['f'])) ? $_GET['f'] : 'main';
        $vars     = get_class_vars(get_class($this));

        if (isset($vars['needAuth']) && $vars['needAuth'] === TRUE){
	        if (Session::getCurrent()->get('username') === NULL){
		        $this->noAccess();
		        exit;
	        }
        }

        if ($function != '' && method_exists($this, $function) && $this->isPublic($function)){
            call_user_func(array($this, $function));
        }
    }

    /**
     * ECHO no access message
     * @return void
     */
    public function noAccess(){
	    echo HTML::redirect(Config::get('siteSettings.rootDir').'/login', 0);
    }
}